package graduation.project.mutant.strategy;

import graduation.project.body.Expression;
import graduation.project.body.Mutants;
import graduation.project.body.OriginExpression;
import graduation.project.exception.NonExpressionException;

import java.util.ArrayList;

public class ENFMutantsGen implements MutantsGenerator {

	public Mutants generateMutants(String expression, int mutantsNum) {
		
		try{
			OriginExpression originEx = new OriginExpression(expression);
			return generateMutants(originEx, mutantsNum);
		}catch(NonExpressionException e){
			System.out.println("ENFMutantsGen: the expression is invalid.");
			e.printStackTrace();
		}
		return null;
	}

	public Mutants generateMutants(OriginExpression originEx, int num) {
		
		Mutants result = new Mutants(originEx.getExpression(),  "ENF");
		ArrayList<Expression> mutantSet = new ArrayList<Expression>();
		String idnf = originEx.getIDNF();
		String[] terms = idnf.split("\\+");
		int count = 0;
		boolean isFull = false;
		
		StringBuffer exp = new StringBuffer();
		exp.append(idnf);
		int beginPos;
		int endPos;
		for(int i = 0; i < terms.length - 1; i++){
			for(int j = 2; j <= terms.length; j++){
				beginPos = exp.indexOf(terms[i]);
				exp.insert(beginPos, "!(");
				if(i + j - 1 >= terms.length)
					break;
				endPos = exp.indexOf(terms[i + j - 1]);
				exp.insert(endPos + terms[i + j -1].length(), ")");				
				try {
					mutantSet.add(new Expression(exp.toString()));
				} catch (NonExpressionException e) {
					System.out.println("ENFMutantsGen: the expression is invalid.");
					e.printStackTrace();
				}
				beginPos = exp.indexOf(terms[i]);
				exp.delete(beginPos - 2, beginPos);
				endPos = exp.indexOf(terms[i + j - 1]);
				exp.deleteCharAt(endPos + terms[i + j - 1].length());
				
				if(num != -1 && ++count >= num){
					isFull = true;
					break;
				}
			}
			if(isFull)
				break;
		}
				
		result.setMutants(mutantSet);		
		return result;
	}

}
